import moment from 'moment';
import { getGamesRun } from '../../services/financial';
import initTemplate from '../../utils/reportTemplate';

const MONTH = moment().format('YYYY-MM');

export default {
    namespace: 'games',
    state: {
        data: [],
        searchInfo: {
            type: 'month',
            date: MONTH,
        },
        storeID: ''
    },
    subscriptions: {
        setup(args) {
            const { dispatch, history } = args;
            history.listen(({ pathname }) => {
                if (pathname === '/analysis/games') {
                    dispatch({
                        type: 'init',
                    });
                }
            });
        }
    },
    effects: {
        * init({ storeId: storeID = '' }, { put }) {
            yield put({
                type: 'upState',
                payload: {
                    storeID,
                },
            });
            yield put({
                type: 'load',
            });
        },
        * load(p, { put, call, select }) {
            const { searchInfo, storeId: storeID } = yield select(({ games, app: { user } }) => ({
                ...games,
                ...user
            }));
            const { data, code, msg } = yield call(getGamesRun, { ...searchInfo, storeID });
            if (code === '0000') {
                const { gameAll, gameRunStatisticsDTOList: report } = data;
                const template = initTemplate({
                    type: 'games',
                    category: 'games',
                    data: report,
                    templateData: gameAll,
                });
                yield put({
                    type: 'upState',
                    payload: {
                        data: template,
                        gameAll,
                    }
                });
            } else {
                console.error(msg);
            }
        },
        * changeSearchType({ searchInfo }, { put }) {
            console.log('searchInfo', searchInfo);
            yield put({
                type: 'upState',
                payload: { searchInfo },
            });
            yield put({
                type: 'load',
            });
        },
    },
    reducers: {
        upState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
    }
};
